<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="onClose"
  >

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="登录账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            :disabled="!!model.id"
            placeholder="请输入登录账号"
            v-decorator="['loginName',{ rules: [
              { required: true, message: '请输入登录账号!' }
            ] }]"
          />
        </a-form-item>

        <a-form-item label="用户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-input
            placeholder="请输入用户姓名"
            v-decorator="['userName',{rules: [{ required: true, message: '请输入用户姓名!' }]}]"
          />
        </a-form-item>

        <a-form-item label="员工编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入员工编号"
            v-decorator="['employeeCode',{ rules: [
              { required: false, message: '请输入员工编号!' }
            ] }]"
          />
        </a-form-item>

        <template v-if="!model.id">
          <a-form-item label="登陆密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
            <a-input
              autoComplete="new-password"
              type="password"
              placeholder="请输入登陆密码"
              v-decorator="['pwd',{ rules: [
                { required: true, message: '请输入登陆密码!' },
                { validator: validateToNextPassword }
              ] }]"
            />
          </a-form-item>

          <a-form-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
            <a-input
              type="password"
              @blur="handleConfirmBlur"
              placeholder="请重新输入登陆密码"
              v-decorator="['confirmpwd',{ rules: [
                { required: true, message: '请重新输入登陆密码!' },
                { validator: compareToFirstPassword }
              ] }]"
            />
          </a-form-item>
        </template>

        <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-decorator="[ 'gender', {}]" placeholder="请选择性别">
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="2">女</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="角色分配" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择用户角色"
            optionFilterProp="children"
            v-decorator="['roleIds', { rules: [
              { required: true, message: '请选择用户角色!' }
            ] }]"
          >
            <a-select-option v-for="(role,roleindex) in roleList" :key="roleindex.toString()" :value="role.id">
              {{ role.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入手机号码" v-decorator="[ 'mobile', {rules: [{ required: false, pattern: mobilePattern, message: '请输入正确的手机号码!' }]}]" />
        </a-form-item>
        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-decorator="['status', {rules: [{ required: true, message: '请选择用户状态!' }]}]" button-style="solid">
            <a-radio-button v-for="(item,index) in userStatusEnum" :key="index" :value="item.KEY">
              {{ item.NAME }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
    <div class="drawer-bottom-button">
      <a-button :style="{marginRight: '8px'}" @click="onClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import pick from 'lodash.pick'
import { apiQueryRoleList, apiQueryUserById, apiAddUser, apiEditUser } from '@/api/system'
import { FormModalMixin } from '@/mixins/FormModalMixin'
import { USER_GENDER_ENUM, USER_STATUS_ENUM } from '@/store/mutation-types'

export default {
  name: 'UserModal',
  components: {
    TreeSelect
  },
  mixins: [FormModalMixin],
  data () {
    return {
      roleList: [],
      passwordPattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
      mobilePattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/,
      confirmDirty: false,
      userGenderEnum: USER_GENDER_ENUM,
      userStatusEnum: USER_STATUS_ENUM
    }
  },
  mounted () {
    // 角色列表
    this.initialRoleList()
  },
  methods: {
    initialRoleList () {
      apiQueryRoleList().then((res) => {
        if (res.code === 1) {
          this.roleList = res.data.content
        }
      })
    },
    show (title, record) {
      this.resetFields()
      this.model = {}
      this.visible = true
      this.title = title
      if (record) {
        apiQueryUserById(record.id).then(res => {
          this.model = Object.assign({}, res.data)
          this.$nextTick(() => {
            if (!this.model.roleIds) {
              delete this.model.roleIds
            }
            this.form.setFieldsValue(pick(this.model, 'employeeCode', 'loginName', 'pwd', 'userName', 'gender', 'roleIds', 'mobile', 'status'))
          })
        })
      }
    },
    onClose () {
      this.visible = false
    },
    validateToNextPassword  (rule, value, callback) {
      console.log('validateToNextPassword', rule, value)
      const form = this.form
      if (!new RegExp(this.passwordPattern).test(value)) {
        // eslint-disable-next-line
        callback('密码由8位数字、大小写字母和特殊符号组成!')
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirmpwd'], { force: true })
      }
      callback()
    },
    compareToFirstPassword  (rule, value, callback) {
      console.log('compareToFirstPassword', rule, value)
      const form = this.form
      if (value && value !== form.getFieldValue('pwd')) {
        // eslint-disable-next-line
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    handleConfirmBlur  (e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
      console.log(this.confirmDirty, !!value)
    },
    handleSubmit () {
      console.log('handleSubmit')
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        console.log(err)
        if (!err) {
          console.log(values)
          that.confirmLoading = true
          const formData = pick(Object.assign(this.model, values), 'employeeCode', 'loginName', 'pwd', 'userName', 'gender', 'roleIds', 'mobile', 'status')
          let obj
          if (!this.model.id) {
            // formData.id = this.userId
            obj = apiAddUser(formData)
          } else {
            delete formData.pwd
            obj = apiEditUser(this.model.id, formData)
          }
          obj.then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }

  }
}
</script>

<style scoped>
.drawer-bottom-button {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
}
</style>
